import React, {useState, useEffect} from 'react';
import {
  FlatList,
  RefreshControl,
  ActivityIndicator,
  View,
  Text,
} from 'react-native';

const NoDataComponent = () => {
  return <Text>暂无数据</Text>;
};

const ErrorComponent = () => {
  return <Text>加载失败</Text>;
};

function PullRefreshList({
  renderItem,
  keyExtractor,
  data,
  onFetchData,
  initialPage = 1,
  pageSize = 10,
  refreshControlProps,
}) {
  // 初始化 state
  const [page, setPage] = useState(initialPage);
  const [isLoading, setIsLoading] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [hasMoreData, setHasMoreData] = useState(true);

  // 当 page 发生变化时，重新获取数据
  useEffect(() => {
    fetchData();
  }, [page]);

  // 获取数据
  const fetchData = async () => {
    // 判断是否需要分页获取
    if (!hasMoreData || isLoading) {
      return;
    }

    setIsLoading(true);
    try {
      const newData = await onFetchData(page);
      if (newData.length < pageSize) {
        // 如果返回的数据少于 pageSize，说明没有更多数据了
        setHasMoreData(false);
      }
      // 将新数据添加到现有数据后面
      setData([...data, ...newData]);
    } catch (error) {
      console.log(error);
    }
    setIsLoading(false);
  };

  // 刷新数据
  const refreshData = async () => {
    if (isRefreshing) {
      return;
    }

    setIsRefreshing(true);
    setPage(initialPage);
    setHasMoreData(true);
    try {
      const newData = await onFetchData(initialPage);
      setData(newData);
    } catch (error) {
      console.log(error);
    }
    setIsRefreshing(false);
  };

  // 渲染每个 item
  const renderItemWithIndex = ({item, index}) => renderItem(item, index);

  // 渲染 FlatList
  return (
    <FlatList
      data={data}
      renderItem={renderItemWithIndex}
      keyExtractor={keyExtractor}
      refreshControl={
        <RefreshControl
          refreshing={isRefreshing}
          onRefresh={refreshData}
          {...refreshControlProps}
        />
      }
      onEndReachedThreshold={0.1}
      onEndReached={fetchData}
      ListFooterComponent={
        isLoading ? (
          <ActivityIndicator size="large" />
        ) : (
          !hasMoreData && (
            <View>
              {!data.length ? NoDataComponent : null}
              {/* {error ? ErrorComponent : null} */}
            </View>
          )
        )
      }
    />
  );
}

export default PullRefreshList;
